package ptotocol

import (
	"bufio"
	"io"
	"log"
	"strings"
)

type Reader struct {
	reader *bufio.Reader
}

func NewReader(reader io.Reader) *Reader {
	return &Reader{reader: bufio.NewReader(reader)}
}

func (r *Reader) Read() (interface{}, error) {
	cmd, err := r.reader.ReadString(' ')

	if err != nil {
		return nil, err
	}

	cmd = strings.TrimSpace(cmd)

	switch cmd {
	case "MESS":
		user, err := r.reader.ReadString(' ')
		if err != nil {
			return nil, err
		}
		message, err := r.reader.ReadString('\n')
		return MessCmd{Name: user, Msg: message}, err
	case "SEND":
		message, err := r.reader.ReadString('\n')
		if err != nil {
			return nil, err
		}
		return SendCmd{
			Msg: message,
		}, err
	case "NAME":
		name, err := r.reader.ReadString('\n')
		if err != nil {
			return nil, err
		}
		return NameCmd{Name: name}, err
	default:
		log.Printf("Unrecognized command: %v", cmd)
	}

	return nil, UnknownCommand
}

func (r *Reader) ReadAll() ([]interface{}, error) {
	commands := []interface{}{}
	for {
		command, err := r.Read()
		if command != nil {
			commands = append(commands, command)
		}

		if err == io.EOF {
			break
		} else if err != nil {
			return commands, err
		}

	}
	return commands, nil
}
